package com.srit.recipes.service.impl;

import com.srit.recipes.common.exception.RecipesException;
import com.srit.recipes.common.parent.DaoInject;
import com.srit.recipes.common.response.JpaPage;
import com.srit.recipes.common.utils.JwtUtil;
import com.srit.recipes.entity.UserInfo;
import com.srit.recipes.service.UserService;
import com.srit.recipes.vo.UserBean;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends DaoInject implements UserService {
    @Override
    public Object login(String phone, String password) {
        UserInfo user = userDao.findByPhone(phone);

        if (user == null) {
            throw RecipesException.of("user is not exist");
        }

        if (user.getPassword().equals(password)) {
            UserBean userBean = new UserBean();
            userBean.setId(user.getId());
            userBean.setName(user.getName());
            userBean.setPhone(user.getPhone());
            userBean.setRole(user.getRole());
            String token = JwtUtil.generateToken(user.getId());
            userBean.setToken(token);
            return userBean;

        }

        throw RecipesException.of("password is wrong");
    }

    @Override
    public Object userList(JpaPage jpaPage) {
        return JpaPage.build(userDao.findAll(JpaPage.getPageable(jpaPage)));
    }

    @Override
    public Object userUpdate(UserInfo userInfo) {
        return userDao.save(userInfo);
    }

    @Override
    public Object deleteUser(long id) {
        userDao.deleteById(id);
        return true;
    }
}
